import { parse } from 'querystring';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => {
  const hrefArr = window.location.href.split('?');
  if (hrefArr && hrefArr.length > 1) {
    return parse(hrefArr[1]);
  }
  return null;
};

/**
 * @name: Function tableKey
 * @test: 添加表格key值
 * @param {companyName:^data,current,pageSize}
 * @return:  ReactDOM
 */
export function tableKey(data: any, current: number, pageSize: number) {
  if (data.length) {
    for (var i = 0; i < data.length; i++) {
      data[i].key = (current - 1) * pageSize + i + 1;
    }
  }
}

interface arrType {
  key?: string;
  value?: number;
}

interface addressR {
  provinceName?: string;
  provinceCode?: number | string;
  regionName?: string;
  regionCode?: number | string;
  cityName?: string;
  cityCode?: number | string;
}
/**
 *  解析地址array
 * @param array
 */
export function setAddressValue(array: arrType[]): addressR {
  return {
    provinceName: array?.[0]?.key ?? '',
    provinceCode: array?.[0]?.value ?? '',
    cityName: array?.[1]?.key ?? '',
    cityCode: array?.[1]?.value ?? '',
    regionName: array?.[2]?.key ?? '',
    regionCode: array?.[2]?.value ?? '',
  };
}

/**
 * 组装组件需要的省市区格式
 * @param obj
 */
export function setAddressList(obj: any): arrType[] {
  return [
    {
      key: obj?.provinceName,
      value: obj?.provinceCode,
    },
    {
      key: obj?.cityName,
      value: obj?.cityCode,
    },
    {
      key: obj?.regionName,
      value: obj?.regionCode,
    },
  ];
}
